import {Component, OnInit, ViewEncapsulation, Input, Renderer, OnDestroy, ChangeDetectorRef} from '@angular/core';
import {ToolsService} from "../../service/tools/tools.service";
import {EventsService} from "../../../core/events/events.service";

@Component({
  selector: 'seed-modal',
  templateUrl: './modal.component.html',
  styleUrls: ['./modal.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class ModalComponent implements OnInit, OnDestroy {
  public _window: any;
  public visible = false;
  public visibleAnimate = false;
  public listenHander: Function;
  private _content;
  @Input()
  get content() {
    return this._content;
  }

  set content(value) {
    this._content = value;
  }

  constructor(private tools: ToolsService,
              public renderer: Renderer,
              private events: EventsService,
              private cdr: ChangeDetectorRef) {
    this._window = this.tools.nativeWindow;
    this.events.subscribe('modal:show', () => {
      if (!this.visible) { this.show(); };
    });
    this.events.subscribe('modal:close', () => {
      if (this.visible) {
        this.hide();
        this.goBack();
      }
    });
  }

  public show(): void {
    this.visible = true;
    this.pushState();
    setTimeout(() => {
      this.visibleAnimate = true;
      try {
        this.cdr.detectChanges();
      } catch (e) {
        // console.log(e)
      }
      /*if(!this.cdr.detach()){
       this.cdr.detectChanges();
       }*/

    }, 100);
    // console.log(this.content)
    if (this.content) {

      this.content.enableScroll();
    }
  }

  public goBack() {
    window.history.back();
  }

  public hide(): void {
    this.visibleAnimate = false;
    if (this.content) {
      this.content.enableScroll(true);
    }
    setTimeout(() => {
      this.visible = false;
 /*     if(!this.cdr.detach()){
        this.cdr.detectChanges();
      }*/
      try {
        this.cdr.detectChanges();
      } catch (e) {
        console.log(e);
      }
    }, 300);
  }

  getPushURL() {
    let array = [window.location.href.split('#')[0], window.location.hash];
    array.push(window.location.href.indexOf('?') === -1 ? '?' : '&');
    array.push('popup=' + Math.random().toString(36).substr(2));
    return array.join('');
  }

  pushState() {
    if (window.location.href.indexOf('popup=') > 1) {
      const location = window.location.href,
      url = location.substring(location.indexOf('popup=') - 1, -1);
      window.history.replaceState({}, '', url);
    }
    if (window.location.href.indexOf('popup=') === -1) {
      window.history.pushState({}, '', this.getPushURL());
      const popstateHandler = () => {
        this.hide();
        if (this.listenHander) {
          this.listenHander();
        }
      };
      this.listenHander = this.renderer.listenGlobal('window', 'popstate', popstateHandler.bind(this));
    }
  }

  onContainerClicked(event: MouseEvent): void {
    if ((<HTMLElement>event.target).classList.contains('seed-modal-backdrop')) {
      this.hide();
      this.goBack();
    }
  }

  ngOnInit() {
  }

  ngOnDestroy() {
    if (this.listenHander) { this.listenHander(); };
  }

}
